//
//  CProduct.m
//  HCHK_iphone
//
//  Created by yilong zhang on 11-12-11.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "CProduct.h"

@implementation CProduct

@synthesize delegate;

@synthesize P_AID;
@synthesize P_Name;
@synthesize P_Price;
@synthesize P_UrlIcon;
@synthesize P_Icon;
@synthesize P_UrlImage;
@synthesize P_Image;
@synthesize P_Position;
@synthesize P_Caption;
@synthesize P_ResName;
@synthesize P_JDu;
@synthesize P_WDu;
@synthesize P_Eat;
@synthesize P_Want;
@synthesize P_Nice;
@synthesize P_Date;
@synthesize P_City;
@synthesize P_Publisher;
@synthesize P_PubName;
@synthesize P_PubIcon;
@synthesize P_PubIconUrl;
@synthesize P_SubImage;
@synthesize P_SubImgUrl;

@synthesize m_bIsLoadCom;
@synthesize m_AscCounter;
@synthesize m_DesCounter;
@synthesize m_lFollowID;
//@synthesize m_Coms;

//@synthesize m_IsIconNil;
@synthesize m_IsIconLoad;
@synthesize m_IconOpID;

@synthesize m_PubIconOpID;
@synthesize m_IsPubIconLoad;

//@synthesize m_IsImageNil;
@synthesize m_IsImageLoad;
@synthesize m_ImageOpID;

@synthesize m_ComOpID;
@synthesize m_EatOpID;
@synthesize m_WantOpID;
@synthesize m_NiceOpID;

//评价
@synthesize m_bIsEated;
@synthesize m_bIsNiced;
@synthesize m_bIsWanted;

@synthesize m_SubTask;

//commentaries
//@synthesize m_ShowComsTarget;
//@synthesize m_ShowComsAction;

//view
@synthesize m_IconView;
@synthesize m_ImageView;
@synthesize m_PubIconView;

@synthesize m_Index;
@synthesize m_nState;

- (id)init
{
    self = [super init];
    if (self)
    {
        self.m_nState   = -1;
        self.P_Name     = @"好吃客";
        self.P_UrlIcon  = nil;
        self.P_Icon     = nil;
        self.P_UrlImage = nil;
        self.P_Image    = nil;
        self.P_Position = @"好吃客";
        self.P_Caption  = @"好吃";
        self.P_ResName  = @"好吃客";
        self.P_City     = @"西安";
        self.P_PubName  = @"怪侠一枝梅";
        self.P_PubIconUrl = nil;
        self.P_PubIcon  = nil;
        self.P_SubImage = nil;
        self.P_SubImgUrl= nil;
        
        self.P_AID      = [NSNumber numberWithLong:0];
        self.P_JDu      = [NSNumber numberWithFloat:108.54];
        self.P_WDu      = [NSNumber numberWithFloat:34.16];
        self.P_Price    = [NSNumber numberWithFloat:0.0];
        self.P_Eat      = [NSNumber numberWithLong:0];
        self.P_Want     = [NSNumber numberWithLong:0];
        self.P_Nice     = [NSNumber numberWithLong:0];
        self.P_Date     = [NSNumber numberWithLong:0];
        self.P_Publisher= [NSNumber numberWithLong:0];
        
        self.m_IconOpID = nil;
        self.m_ImageOpID= nil;
        self.m_ComOpID  = nil;
        self.m_EatOpID  = nil;
        self.m_WantOpID = nil;
        self.m_NiceOpID = nil;
        self.m_IconView = nil;
        self.m_ImageView= nil;
        
        self.m_bIsNiced = NO;
        self.m_bIsEated = NO;
        self.m_bIsWanted= NO;
        
        self.m_IsImageLoad = NO;
        self.m_IsIconLoad  = NO;
        
        //self.m_ShowComsAction = nil;
        //self.m_ShowComsTarget = nil;
        self.m_bIsLoadCom = NO;
        m_AscCounter = [[CAscCounter alloc] init];
        m_DesCounter = [[CDesCounter alloc] init];
        [self ResetQueryConditions];
        //m_Coms = [[NSMutableArray array] retain];
        
        m_SubTask = [[NSMutableArray array] retain];
    }
    
    return self;
}

-(void)dealloc
{
    [P_AID release];
    [P_Name release];
    [P_UrlIcon release];
    [P_Icon release];
    [P_UrlImage release];
    [P_Image release];
    [P_Position release];
    [P_Caption release];
    [P_ResName release];
    [P_PubName release];
    [P_PubIcon release];
    [P_PubIconUrl release];
    [P_SubImage release];
    [P_SubImgUrl release];
    
    [m_AscCounter release];
    [m_DesCounter release];
    //[m_Coms release];
    [m_IconView release];
    [m_ImageView release];
    
    [P_Date release];
    [P_Eat release];
    [P_Want release];
    [P_Nice release];
    [P_JDu release];
    [P_WDu release];
    [P_City release];
    [P_Publisher release];
    [P_Price release];
    
    m_IconView = nil;
    m_ImageView= nil;
    m_PubIconView=nil;

    delegate = nil;
    
    [[CDownLoadManager DefaultDownLoadManager] CancelTask:m_IconOpID];
    [[CDownLoadManager DefaultDownLoadManager] CancelTask:m_ImageOpID];
    [[CDownLoadManager DefaultDownLoadManager] CancelTask:m_ComOpID];
    //[[CDownLoadManager DefaultDownLoadManager] CancelTask:m_PubIconOpID];
    [m_EatOpID release];
    [m_WantOpID release];
    [m_NiceOpID release];
    
    //[[CDownLoadManager DefaultDownLoadManager] CancelTask:m_EatOpID];
    //[[CDownLoadManager DefaultDownLoadManager] CancelTask:m_WantOpID];
    //[[CDownLoadManager DefaultDownLoadManager] CancelTask:m_NiceOpID];
    //[m_IconOpID release];
    //[m_ImageOpID release];
    //[m_ComOpID release];
    
    [self CancelSubImgTask];
    [m_SubTask release];
    
    [self ProductCancelLoadIcon];
    [self ProductCancelLoadImage];
    [self ProductCancelLoadComs];
    [self ProductCancelLoadPubIcon];
    
    [super dealloc];
}

+(int)CreateProdutTable:(NSString*)tablename
{
    NSMutableArray *keys = [NSMutableArray array];
    CKey *key = nil;
    
    key = [[CKey alloc] initWithType:1 Length:32 Name:@"P_AID" Primary:YES];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:32 Name:@"P_Name" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:2 Length:32 Name:@"P_Price" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:150 Name:@"P_UrlIcon" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:150 Name:@"P_Icon" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:150 Name:@"P_UrlImage" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:150 Name:@"P_Image" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:32 Name:@"P_Position" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:300 Name:@"P_Caption" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:64 Name:@"P_City" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Length:32 Name:@"P_Publisher" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:32 Name:@"P_PubName" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:50 Name:@"P_ResName" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Length:32 Name:@"P_Eat" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Length:32 Name:@"P_Want" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Length:32 Name:@"P_Nice" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Length:32 Name:@"P_Date" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:2 Length:32 Name:@"P_JDu" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:2 Length:32 Name:@"P_WDu" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:150 Name:@"P_PubIcon" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:150 Name:@"P_PubIconUrl" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:1200 Name:@"P_SubImgUrl" Primary:NO];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Length:32 Name:@"P_SubImage" Primary:NO];
    [keys addObject:key];
    [key release];
    
    return [[CDBManager ScheduledShareInstance] CreateTable:tablename Keys:keys];
}

+(int)GetProuctsTotal:(NSString*)tablename Where:(NSString*)where
{
    return [[CDBManager ScheduledShareInstance] GetRecordTotal:@"Products" Condition:where Key:@"P_AID"];
}

+(NSArray*)GetLimitProducts:(NSString*)tablename Where:(NSString*)where Offset:(int)offset Limit:(int)limit;
{
    NSArray         *keys  = [NSArray arrayWithObjects:@"*", nil];
    NSArray         *rets  = nil;
    NSMutableArray  *prdcts= [NSMutableArray array];
    CProduct        *prdct = nil;
    
    rets = [[CDBManager ScheduledShareInstance] QueryRecordsFromCursor:tablename Keys:keys Offset:offset Limit:limit Column:Product_Properties_Num Condition:where];
    
    if (rets && [rets count] > 0)
    {
        for (int i=0; i<[rets count]; i++)
        {
            prdct = [[CProduct alloc] init];
            [prdct SetProductWithArr:[rets objectAtIndex:i]];
            [prdcts addObject:prdct];
            [prdct release];
        }
        
        return prdcts;
    }
    
    return nil;
}

+(int)UpdateProductInfo:(NSString*)tablename Where:(NSString*)where Keys:(NSArray*)keys
{
    return [[CDBManager ScheduledShareInstance] UpdateRecordInfo:tablename Keys:keys Condition:where];
}

+(int)RemoveProduct:(NSString*)tablename Where:(NSString*)where
{
    return [[CDBManager ScheduledShareInstance] DeleteRecord:tablename Condition:where];
}

-(void)SetProductWithArr:(NSArray*)arr
{
    if (arr)
    {
        int nCnt = 0;
        id  objc = nil;
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_AID      = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_Name     = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_Price    = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_UrlIcon  = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_Icon     = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_UrlImage = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_Image    = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_Position = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_Caption = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_City     = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_Publisher= ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_PubName  = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_ResName  = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_Eat      = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_Want     = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_Nice     = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_Date     = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_JDu      = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_WDu      = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_PubIcon  = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_PubIconUrl  = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_SubImgUrl   = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
        
        objc = [arr objectAtIndex:nCnt++];
        self.P_SubImage  = ([objc isKindOfClass:[NSNull class]]) ? (nil) : (objc);
    }
}

-(void)SetProductWithDic:(NSDictionary*)dic Path:(NSString*)path
{
    self.P_AID      = [NSNumber numberWithLong:[[dic objectForKey:@"pic_id"] intValue]];
    self.P_Name     = [dic objectForKey:@"pic_name"];
    self.P_UrlIcon  = [dic objectForKey:@"pic_thumb"];
    self.P_Icon     = [NSString stringWithFormat:@"%@/%@_icon.jpg", path, [dic objectForKey:@"pic_id"]];
    self.P_UrlImage = [dic objectForKey:@"pic_path"];
    self.P_Image    = [NSString stringWithFormat:@"%@/%@_image.jpg", path, [dic objectForKey:@"pic_id"]];
    self.P_Position = [dic objectForKey:@"pic_addr"];
    self.P_Caption  = [dic objectForKey:@"pic_caption"];
    self.P_ResName  = [dic objectForKey:@"restaurant"];
    self.P_JDu      = [NSNumber numberWithFloat:[[dic objectForKey:@"pic_y"] floatValue]];
    self.P_WDu      = [NSNumber numberWithFloat:[[dic objectForKey:@"pic_x"] floatValue]];
    self.P_Eat      = [NSNumber numberWithLong:[[dic objectForKey:@"tasty"] intValue]];
    self.P_Want     = [NSNumber numberWithLong:[[dic objectForKey:@"want"] intValue]];
    self.P_Nice     = [NSNumber numberWithLong:[[dic objectForKey:@"beautiful"] intValue]];
    self.P_Date     = [NSNumber numberWithLong:[[AppConfig DefaultAppConfig] DateToInt:[dic objectForKey:@"pic_time"]]];
    self.P_City     = [dic objectForKey:@"city"];
    self.P_Publisher= [NSNumber numberWithLong:[[dic objectForKey:@"user_id"] intValue]];
    self.P_PubName  = [dic objectForKey:@"user_nicename"];
    self.P_PubIcon  = [NSString stringWithFormat:@"%@/%ld_icon.jpg", [AppConfig DefaultAppConfig].m_IConsPath, [self.P_Publisher longValue]];
    self.P_PubIconUrl=[dic objectForKey:@"user_img"];
    self.P_SubImgUrl= [dic objectForKey:@"pic_NDYD"];
    if ([self.P_SubImgUrl length] > 5)
        self.P_SubImage = [NSString stringWithFormat:@"%d", [[self.P_SubImgUrl componentsSeparatedByString:@"||"] count]];
    else 
        self.P_SubImage = [NSString stringWithFormat:@"%d", 0];
    NSLog(@"--SubImgUrl of Product:%@\r\n", self.P_SubImgUrl);
    
    //do not save
    self.m_lFollowID= [[dic objectForKey:@"followid"] intValue];

    return;
    
    /*id ret = [dic objectForKey:@"comment"];
    if ([ret isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *subdic = nil;
        CCommentary *com = nil;
        for (int i=0; i<[ret count]-1; i++)
        {
            subdic = [ret objectForKey:[NSString stringWithFormat:@"%d", i]];
            com = [[CCommentary alloc] init];
            [com SetCommentaryWithDic:subdic];
            if (0 != [com SaveCommentary])
            {
                //NSLog(@"commentary existing.");
            }
            [com release];
        }
    }*/
}

-(int)SaveProduct:(NSString*)tablename
{
    NSMutableArray *keys = [NSMutableArray array];
    CKey *key = nil;
    
    key = [[CKey alloc] initWithType:1 Value:self.P_AID Name:@"P_AID"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_Name Name:@"P_Name"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:2 Value:self.P_Price Name:@"P_Price"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_UrlIcon Name:@"P_UrlIcon"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_Icon Name:@"P_Icon"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_UrlImage Name:@"P_UrlImage"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_Image Name:@"P_Image"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_Position Name:@"P_Position"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_Caption Name:@"P_Caption"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_City Name:@"P_City"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.P_Publisher Name:@"P_Publisher"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_PubName Name:@"P_PubName"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_ResName Name:@"P_ResName"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.P_Eat Name:@"P_Eat"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.P_Want Name:@"P_Want"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.P_Nice Name:@"P_Nice"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.P_Date Name:@"P_Date"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:2 Value:self.P_JDu Name:@"P_JDu"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:2 Value:self.P_WDu Name:@"P_WDu"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_PubIcon Name:@"P_PubIcon"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_PubIconUrl Name:@"P_PubIconUrl"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_SubImgUrl Name:@"P_SubImgUrl"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_SubImage Name:@"P_SubImage"];
    [keys addObject:key];
    [key release];
    
    return [[CDBManager ScheduledShareInstance] InsertNewRecordToTable:tablename Keys:keys];
}

-(int)SaveProductWithPathes:(NSString*)table IconPath:(NSString*)iconpath ImagePath:(NSString*)imagepath
{
    NSMutableArray *keys = [NSMutableArray array];
    CKey *key = nil;
    
    key = [[CKey alloc] initWithType:1 Value:self.P_AID Name:@"P_AID"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_Name Name:@"P_Name"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:2 Value:self.P_Price Name:@"P_Price"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_UrlIcon Name:@"P_UrlIcon"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:iconpath Name:@"P_Icon"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_UrlImage Name:@"P_UrlImage"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:imagepath Name:@"P_Image"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_Position Name:@"P_Position"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_Caption Name:@"P_Caption"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_City Name:@"P_City"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.P_Publisher Name:@"P_Publisher"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_PubName Name:@"P_PubName"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_ResName Name:@"P_ResName"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.P_Eat Name:@"P_Eat"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.P_Want Name:@"P_Want"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.P_Nice Name:@"P_Nice"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:1 Value:self.P_Date Name:@"P_Date"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:2 Value:self.P_JDu Name:@"P_JDu"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:2 Value:self.P_WDu Name:@"P_WDu"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_SubImgUrl Name:@"P_SubImgUrl"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:self.P_SubImage Name:@"P_SubImage"];
    [keys addObject:key];
    [key release];
    
    return [[CDBManager ScheduledShareInstance] InsertNewRecordToTable:table Keys:keys];
}

-(int)SaveIcon:(NSData*)data
{
    if (![[NSFileManager defaultManager] createFileAtPath:self.P_Icon contents:data attributes:nil])
    {
        NSLog(@"save icon of product failed!");
        return 1;
    }
    
    return 0;
}

-(int)SaveImage:(NSData*)data
{
    if (![[NSFileManager defaultManager] createFileAtPath:self.P_Image contents:data attributes:nil])
    {
        NSLog(@"save image of product failed!");
        return 1;
    }
    
    return 0;
}

-(int)SavePubIcon:(NSData*)data
{
    if (![[NSFileManager defaultManager] createFileAtPath:self.P_PubIcon contents:data attributes:nil])
    {
        NSLog(@"save image of product failed!");
        return 1;
    }
    
    return 0;
}

-(void)ResetQueryConditions
{
    m_DesCounter.m_nTotal = -1;
    m_DesCounter.m_nOffset= -1;
    m_DesCounter.m_nLimit = -1;
    
    m_AscCounter.m_nTotal = 0;
    m_AscCounter.m_nLimit = 5;
    m_AscCounter.m_nOffset= 0;
}

-(void)PublicationCommentary:(NSString*)mobikey SessionID:(NSString*)sessionid Content:(NSString*)content TmpID:(NSNumber*)tmpID
{
    NSMutableString *request = [NSMutableString stringWithCapacity:6];
    
    [request appendFormat:@"clientID=%@", [AppConfig DefaultAppConfig].m_strUDID];
    [request appendFormat:@"&mobikey=%@", [CUser DefaultUser].U_Token];
    [request appendFormat:@"&sessionid=%@", [CUser DefaultUser].U_Session];
    [request appendFormat:@"&pic_id=%@", [NSString stringWithFormat:@"%lld", [self.P_AID longLongValue]]];
    [request appendFormat:@"&content=%@", content];
    [request appendFormat:@"&action=%@", @"addComment"];
    
    NSDictionary *temp = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithShort:4], @"other", tmpID, @"ComID", nil];

    self.m_ComOpID = [[CDownLoadManager DefaultDownLoadManager] AddTask:URL_COMMENTARY Sponsor:self PostData:[request dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:temp MType:Post UserInfo:nil];
}

-(void)PublicationAppraisal:(NSString*)mobikey SessionID:(NSString*)sessionid Type:(int)type
{
    NSMutableString *request = [NSMutableString string];
    
    [request appendFormat:@"pic_id=%@", [NSString stringWithFormat:@"%lld", [self.P_AID longLongValue]]];
    [request appendFormat:@"&action=%@", @"setAppraise"];
    [request appendFormat:@"&mobikey=%@", mobikey];
    [request appendFormat:@"&sessionid=%@", sessionid];
    NSLog(@"\r\n\r\n评价请求:%@\r\n\r\n", request);
    
    //eat
    if (4 == type)
    {
        if (!m_bIsEated)
        {
            [request appendFormat:@"&appraise=%@", @"tasty"];
            self.m_EatOpID = [[CDownLoadManager DefaultDownLoadManager] AddTask:URL_APPRAISAL Sponsor:self PostData:[request dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:[NSNumber numberWithShort:30] MType:Post UserInfo:nil];
            m_bIsEated = YES;
        }
        else 
        {
            [delegate DidDownLoadSuccess:self OpType:3 Index:0 Info:@"已经评价过了"];
            return;
        }
    }
    //want
    else if (6 == type)
    {
        if (!m_bIsWanted)
        {
            [request appendFormat:@"&appraise=%@", @"want"];
            self.m_WantOpID = [[CDownLoadManager DefaultDownLoadManager] AddTask:URL_APPRAISAL Sponsor:self PostData:[request dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:[NSNumber numberWithShort:31] MType:Post UserInfo:nil];
            m_bIsWanted = YES;
        }
        else 
        {
            [delegate DidDownLoadSuccess:self OpType:3 Index:1 Info:@"已经评价过了"];
            return;
        }
    }
    //nice
    else if (5 == type)
    {
        if (!m_bIsNiced)
        {
            [request appendFormat:@"&appraise=%@", @"beautiful"];
            self.m_NiceOpID = [[CDownLoadManager DefaultDownLoadManager] AddTask:URL_APPRAISAL Sponsor:self PostData:[request dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:[NSNumber numberWithShort:32] MType:Post UserInfo:nil];
            m_bIsNiced = YES;
        }
        else 
        {
            [delegate DidDownLoadSuccess:self OpType:3 Index:2 Info:@"已经评价过了"];
            return;
        }
    }
    else 
    {
        return;
    }
}

-(void)GetCommentaries
{
    if (![self GetCommentariesFromDB])
    {
        [self DownLoadCommentary];
    }
}

-(BOOL)GetCommentariesFromDB
{
    if (-1 == m_DesCounter.m_nTotal)
    {
        m_DesCounter.m_nTotal = [CCommentary GetCommsTotal:[NSString stringWithFormat:@"P_AID==%ld", [self.P_AID longValue]]];
        if (m_DesCounter.m_nTotal > 0) 
        {
            [m_DesCounter InitDesWithCout:m_DesCounter.m_nTotal Limit:5];
        }
        else 
        {
            return NO;
        }
    }
    
    if (m_DesCounter.m_nTotal > 0 && m_DesCounter.m_nLimit > 0)
    {
        if (!m_bIsLoadCom)
        {
            m_bIsLoadCom = YES;
            
            NSArray *coms = [CCommentary GetLimitCommentaries:[NSString stringWithFormat:@"P_AID==%ld", [self.P_AID longValue]] Offset:m_DesCounter.m_nOffset Limit:m_DesCounter.m_nLimit];
            if ([coms count] > 0 && nil != coms)
            {
                [delegate DidDownLoadCommentaries:self Commetaries:coms];
                [m_DesCounter GetDesNextLimit];
            }
            
            m_bIsLoadCom = NO;
            
            return YES;
        }
    }
    
    return NO;
}

-(NSData*)GetProductIcon
{    
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:self.P_Icon];
    if (nil == data)
    {
        [self DownLoadIcon];
    }
    /*else 
    {
        m_IsIconNil = NO;
    }*/
    
    return data;
}

-(NSData*)GetProductImage
{
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:self.P_Image];
    if (nil == data)
    {
        [self DownLoadImage];
    }
    
    return data;
}

-(NSData*)GetPubIcon
{
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:self.P_PubIcon];
    if (nil == data)
    {
        [self DownLoadPubIcon];
    }
    
    return data;
}

//view

-(void)DownLoadIcon
{
    if (!m_IsIconLoad)
    {
        m_IsIconLoad = YES;
        self.m_IconOpID = [[CDownLoadManager DefaultDownLoadManager] AddTask:self.P_UrlIcon Sponsor:self PostData:nil TimeOut:10 Data:[NSNumber numberWithShort:0] MType:Get UserInfo:nil];
    }
}

-(void)DownLoadImage
{
    if (!m_IsImageLoad)
    {
        m_IsImageLoad = YES;
        self.m_ImageOpID = [[CDownLoadManager DefaultDownLoadManager] AddTask:self.P_UrlImage Sponsor:self PostData:nil TimeOut:10 Data:[NSNumber numberWithShort:1] MType:Get UserInfo:nil];
    }
}

-(void)DownLoadPubIcon
{
    if (!m_IsPubIconLoad)
    {
        m_IsPubIconLoad = YES;
        self.m_PubIconOpID = [[CDownLoadManager DefaultDownLoadManager] AddTask:self.P_PubIconUrl Sponsor:self PostData:nil TimeOut:10 Data:[NSNumber numberWithShort:3] MType:Get UserInfo:nil];
    }
}

-(void)DownLoadCommentary
{
    if (!m_bIsLoadCom)
    {
        if (m_AscCounter.m_nLimit > 0)
        {
            m_bIsLoadCom = YES;
            
            NSMutableString *request = [NSMutableString stringWithCapacity:5];
            
            //[request appendFormat:@"mobikey=%@", [CUser DefaultUser].U_Token];
            //[request appendFormat:@"&sessionid=%@", [CUser DefaultUser].U_Session];
            [request appendFormat:@"clientID=%@", [AppConfig DefaultAppConfig].m_strUDID];
            [request appendFormat:@"&pic_id=%@", [NSString stringWithFormat:@"%ld", [self.P_AID longValue]]];
            [request appendFormat:@"&cursor=%d", m_AscCounter.m_nOffset];
            [request appendFormat:@"&offset=%d", m_AscCounter.m_nLimit];
            [request appendFormat:@"&action=%@", @"getComment"];
            
            self.m_ComOpID = [[CDownLoadManager DefaultDownLoadManager] AddTask:URL_GETCOMMS Sponsor:self PostData:[request dataUsingEncoding:NSUTF8StringEncoding]TimeOut:10 Data:[NSNumber numberWithShort:2] MType:Post UserInfo:nil];
            
            NSLog(@"\r\n\r\n<--------向服务器请求商品评论\r\n\r\n");
        }
    }
}

-(void)SetProductIconView:(id)view
{
    self.m_IconView = view;
}

-(void)SetProductImageView:(id)view
{
    self.m_ImageView = view;
}

-(void)SetPdctPubIconView:(id)view
{
    self.m_PubIconView = view;
}

-(void)CancelSubImgTask
{
    for (CTask *task in m_SubTask)
    {
        [[CDownLoadManager DefaultDownLoadManager] CancelTask:task];
    }
    
    [m_SubTask removeAllObjects];
}

-(void)DownLoadSubImage:(NSString*)url Object:(id)object Number:(NSNumber*)number
{
    //NSArray *info = [[NSArray alloc] initWithObjects:object, [NSNumber numberWithInt:[m_SubTask count]], number, nil];
    CTask *task = [[CDownLoadManager DefaultDownLoadManager] AddTask:self.P_UrlIcon Sponsor:self PostData:nil TimeOut:10 Data:[NSNumber numberWithShort:5] MType:Get UserInfo:[NSArray arrayWithObjects:object, number, nil]];
    [m_SubTask addObject:task];
}

-(void)SaveSubImage:(int)index Data:(NSData *)data
{
    if (data)
    {
        NSString *path = [NSString stringWithFormat:@"%@/Documents/DeliciousImages/%ld_%d.jpg", NSHomeDirectory(), [self.P_AID longValue], index];
        if (![data writeToFile:path atomically:YES])
        {
            NSLog(@"保存subimage失败");
        }
    }
}

-(NSData*)GetSubImage:(int)index
{
    NSString *path = [NSString stringWithFormat:@"%@/Documents/DeliciousImages/%ld_%d.jpg", NSHomeDirectory(), [self.P_AID longValue], index];
    NSData *data = [NSData dataWithContentsOfFile:path];
    
    return data;
}

//download task
-(void)ProductCancelLoadIcon
{
    if (self.m_IconOpID)
    {
        [[CDownLoadManager DefaultDownLoadManager] CancelTask:self.m_IconOpID];
        //[self.m_IconOpID release];
        self.m_IconOpID = nil;
    }
}

-(void)ProductCancelLoadImage
{
    if (self.m_ImageOpID)
    {
        [[CDownLoadManager DefaultDownLoadManager] CancelTask:self.m_ImageOpID];
        //[self.m_ImageOpID release];
        self.m_ImageOpID = nil;
    }
}

-(void)ProductCancelLoadComs
{
    if (self.m_ComOpID)
    {
        [[CDownLoadManager DefaultDownLoadManager] CancelTask:self.m_ComOpID];
        //[self.m_ComOpID release];
        self.m_ComOpID = nil;
    }
}

-(void)ProductCancelLoadPubIcon
{
    if (self.m_PubIconOpID)
    {
        [[CDownLoadManager DefaultDownLoadManager] CancelTask:self.m_PubIconOpID];
        //[self.m_ComOpID release];
        self.m_PubIconOpID = nil;
    }
}

//delegate(opretion)
-(void)DidOperationFinished:(COperation *)op Data:(NSData *)data Other:(id)other UserInfo:(id)userinfo
{
    if (data)
    {
        NSDictionary *info = nil;
        if ([other isKindOfClass:[NSDictionary class]])
        {
            info = (NSDictionary*)other;
            other = [info objectForKey:@"other"];
        }
        else {;}
        
        //ICON
        if (0 == [other shortValue])
        {
            UIImage *image = [UIImage imageWithData:data];
            if (image)
            {
                [self SaveIcon:data];
                if (m_IconView)
                {
                    m_IconView.image = [UIImage imageWithData:data];
                    m_IconView = nil;
                }
            }
            
            m_IsIconLoad = NO;
            self.m_IconOpID   = nil;
        }
        //IMAGE
        else if (1 == [other shortValue])
        {
            UIImage *image = [UIImage imageWithData:data];
            if (image)
            {
                [self SaveImage:data];
                [delegate DidDownLoadImage:self Image:data];
            }
            
            m_IsImageLoad = NO;
            self.m_ImageOpID   = nil;
        }
        //pubicon
        else if (3 == [other shortValue])
        {
            UIImage *image = [UIImage imageWithData:data];
            if (image)
            {
                [self SavePubIcon:data];
                [delegate DidDownLoadPubIcon:self Image:data];
            }
            
            m_IsImageLoad = NO;
            self.m_ImageOpID   = nil;
        }
        //subimages
        else if (5 == [other shortValue])
        {
            NSArray *info = userinfo;
            [delegate DidDownLoadSubImage:self Image:data Object:[info objectAtIndex:0]];
            
            //[m_SubTask removeObjectAtIndex:[[info objectAtIndex:1] intValue]];
            [self SaveSubImage:[[info objectAtIndex:1] intValue] Data:data];
        }
        //commentary
        else if (2 == [other shortValue])
        {
            //NSLog(@"<====Get Commentaries（start）====>");
            
            NSString *jsonstr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSDictionary *dic = [jsonstr JSONValue];
            
            if (dic)
            {
                int nCode = [[dic objectForKey:@"Msg_error"] intValue];
                if (0 == nCode)
                {
                    CCommentary  *com = nil;
                    int nTotal = [[dic objectForKey:@"total"] intValue];
                    NSArray *items = [dic objectForKey:@"Resource"];
                    
                    //判断数据有效性
                    if (m_AscCounter.m_nOffset >= nTotal)
                    {
                        //数据已经存在
                        [jsonstr release];
                        return;
                    }
                    
                    NSDictionary *subdic = nil;
                    NSMutableArray *coms  = [NSMutableArray arrayWithCapacity:[items count]];
                    for (int i=0; i<[items count]; i++)
                    {
                        subdic = [items objectAtIndex:i];
                        com = [[CCommentary alloc] init];
                        if ([subdic isKindOfClass:[NSDictionary class]])
                        {
                            [com SetCommentaryWithDic:subdic];
                            if (0 != [com SaveCommentary])
                            {
                                //NSLog(@"commentary existing.");
                            }
                            else 
                            {
                                [coms addObject:com];
                            }
                        }
                        [com release];
                    }
                    
                    [m_AscCounter GetAscNextLimit:nTotal Cnt:[items count]];
                    
                    [delegate DidDownLoadCommentaries:self Commetaries:coms];
                }
                else 
                {
                    [delegate DidDownLoadError:self OpType:2];
                }
            }
            else 
            {   
                NSLog(@"json error:%@", jsonstr);
                [delegate DidDownLoadError:self OpType:2];
            }
            
            m_bIsLoadCom = NO;
            self.m_ComOpID = nil;
            
            [jsonstr release];
            
            //NSLog(@"<====Get Commentaries（end）====>");
        }
        //appri
        else if ([other shortValue] >= 30)
        {
            NSLog(@"\r\n\r\n<====Get pingjia====>\r\n\r\n");
            
            short op = [other shortValue] - 30;
            NSString *info = nil;
            int code = -1;
            
            NSString *jsonstr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSDictionary *dic = [jsonstr JSONValue];
            NSLog(@"\r\n\r\n========>评价结果:%@__%@__%@\r\n\r\n", dic, jsonstr, [dic objectForKey:@"Msg"]);
            
            //eat
            if (0 == op)
            {
                if (dic)
                {
                    code = [[dic objectForKey:@"Msg_error"] intValue];
                    if (0 == code)
                    {
                        self.P_Eat = [NSNumber numberWithLong:[self.P_Eat longValue]+1];
                        info = (0 == code) ? (@"评价成功") : (@"已经评价过了");
                        [delegate DidDownLoadSuccess:self OpType:3 Index:op Info:info];
                    }
                }
                
                m_bIsEated = NO;
                self.m_EatOpID = nil;
            }
            //want
            else if (1 == op)
            {
                if (dic)
                {
                    code = [[dic objectForKey:@"Msg_error"] intValue];
                    if (0 == code)
                    {
                        self.P_Want = [NSNumber numberWithLong:[self.P_Want longValue]+1];
                        info = (0 == code) ? (@"评价成功") : (@"已经评价过了");
                        [delegate DidDownLoadSuccess:self OpType:3 Index:op Info:info];
                    }
                }
                
                m_bIsWanted = NO;
                self.m_WantOpID = nil;
            }
            //nice
            else if (2 == op)
            {
                if (dic)
                {
                    code = [[dic objectForKey:@"Msg_error"] intValue];
                    if (0 == code)
                    {
                        self.P_Nice = [NSNumber numberWithLong:[self.P_Nice longValue]+1];
                        info = (0 == code) ? (@"评价成功") : (@"已经评价过了");
                        [delegate DidDownLoadSuccess:self OpType:3 Index:op Info:info];
                    }
                }
                
                m_bIsNiced  = NO;
                self.m_NiceOpID = nil;
            }
            else {;}
            
            [jsonstr release];
        }
        //commitcoms
        else if (4 == [other shortValue])
        {
            NSString *jsonstr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSDictionary *dic = [jsonstr JSONValue];
            NSLog(@"\r\n\r\ncommitcoms___%@___%@\r\n\r\n", [dic objectForKey:@"Msg_error"], [dic objectForKey:@"Msg"]);
            
            long comid = [(NSNumber*)[info objectForKey:@"ComID"] longValue];
            if (0 == [[dic objectForKey:@"Msg_error"] intValue])
            {
                NSNumber *ID = [NSNumber numberWithLong:[[dic objectForKey:@"new_id"] intValue]];
                CKey *key = [[CKey alloc] initWithType:1 Value:ID Name:@"C_AID"];
                NSArray *keys = [NSArray arrayWithObjects:key, nil];
                [CCommentary UpdateCommentary:[NSString stringWithFormat:@"C_AID==%ld", comid] Keys:keys];
                [key release];
                
                [delegate DidDownLoadSuccess:self OpType:4 Index:0 Info:nil];
            }
            else 
            {
                [delegate DidDownLoadError:self OpType:4];
            }
            
            self.m_ComOpID = nil;
            
            [jsonstr release];
        }
        else {;}
    }
}

-(void)DidOperationError:(COperation *)op Error:(NSError *)error Other:(id)other UserInfo:(id)userinfo
{
    if (0 == [other shortValue])
    {
        NSLog(@"\r\n\r\n获得商品缩略图失败\r\n\r\n");
        m_IsIconLoad = NO;
        self.m_IconOpID   = nil;
    }
    else if (1 == [other shortValue])
    {
        NSLog(@"\r\n\r\n获得商品大图失败\r\n\r\n");
        m_IsImageLoad = NO;
        self.m_ImageOpID   = nil;
    }
    else if (2 == [other shortValue])
    {
        m_bIsLoadCom = NO;
        self.m_ComOpID    = nil;
        [delegate DidDownLoadError:self OpType:2];
        NSLog(@"\r\n\r\n获得商品评论失败\r\n\r\n");
    }
    //pingjia
    else if ([other shortValue] >= 30)
    {
        short op = [other shortValue] - 30;
        
        if (0 == op)
        {
            self.m_EatOpID = nil;
            self.m_bIsEated= NO;
        }
        else if (1 == op)
        {
            self.m_WantOpID = nil;
            self.m_bIsWanted= NO;
        }
        else if (2 == op)
        {
            self.m_NiceOpID = nil;
            self.m_bIsNiced = NO;
        }
        else {;}
        
        [delegate DidDownLoadError:self OpType:3];
    }
    //commitcoms
    else if (4 == [other shortValue])
    {
        self.m_ComOpID = nil;
        [delegate DidDownLoadError:self OpType:4];
    }
    else{;}
}

-(void)DidOperationTimeOut:(COperation *)op Other:(id)other UserInfo:(id)userinfo
{
    if (0 == [other shortValue])
    {
        NSLog(@"\r\n\r\n获得商品缩略图超时\r\n\r\n");
        m_IsIconLoad = NO;
        self.m_IconOpID   = nil;
    }
    else if (1 == [other shortValue])
    {
        NSLog(@"\r\n\r\n获得商品大图超时\r\n\r\n");
        m_IsImageLoad = NO;
        self.m_ImageOpID   = NO;
    }
    else if (2 == [other shortValue])
    {
        m_bIsLoadCom = NO;
        self.m_ComOpID    = nil;
        [delegate DidDownLoadError:self OpType:2];
        NSLog(@"\r\n\r\n获得商品评论超时\r\n\r\n");
    }
    //pingjia
    else if ([other shortValue] >= 30)
    {
        short op = [other shortValue] - 30;
        
        if (0 == op)
        {
            self.m_EatOpID = nil;
            self.m_bIsEated= NO;
        }
        else if (1 == op)
        {
            self.m_WantOpID = nil;
            self.m_bIsWanted= NO;
        }
        else if (2 == op)
        {
            self.m_NiceOpID = nil;
            self.m_bIsNiced = NO;
        }
        else {;}
        
        [delegate DidDownLoadError:self OpType:3];
    }
    //commitcoms
    else if (4 == [other shortValue])
    {
        self.m_ComOpID = nil;
        [delegate DidDownLoadError:self OpType:4];
    }
    else {;}
}

@end
